<template>
    <div class="upload-container">
        <div class="upload-header">
            <h1>文档上传</h1>
            <p>上传你的文档以便进行智能问答</p>
        </div>

        <div class="upload-form">
            <form @submit.prevent="uploadDocument" class="form">
                <div class="form-group">
                    <label for="title">文档标题：</label>
                    <input id="title" v-model="formData.title" type="text" placeholder="请输入文档标题" required
                        class="form-input" />
                </div>

                <div class="form-group">
                    <label for="source">文档来源：</label>
                    <input id="source" v-model="formData.source" type="text" placeholder="请输入文档来源（可选）"
                        class="form-input" />
                </div>

                <div class="form-group">
                    <label for="file">选择文件：</label>
                    <div class="file-upload-area" :class="{ 'dragover': isDragOver }" @dragover.prevent="handleDragOver"
                        @dragleave.prevent="handleDragLeave" @drop.prevent="handleDrop">
                        <input id="file" ref="fileInput" type="file" @change="handleFileSelect"
                            accept=".txt,.md,.doc,.docx,.pdf" class="file-input" />
                        <div class="file-upload-content">
                            <div v-if="!selectedFile" class="upload-placeholder">
                                <svg class="upload-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12">
                                    </path>
                                </svg>
                                <p>点击选择文件或拖拽到此处</p>
                                <p class="file-types">支持格式：TXT, MD, DOC, DOCX, PDF</p>
                            </div>
                            <div v-else class="file-selected">
                                <svg class="file-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z">
                                    </path>
                                </svg>
                                <div class="file-info">
                                    <p class="file-name">{{ selectedFile.name }}</p>
                                    <p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
                                </div>
                                <button type="button" @click="clearFile" class="clear-file-btn">
                                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" :disabled="!selectedFile || isUploading" class="upload-btn">
                        <span v-if="!isUploading">上传文档</span>
                        <span v-else class="uploading">
                            <svg class="spinner" viewBox="0 0 24 24">
                                <circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="4"
                                    opacity="0.3"></circle>
                                <circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="4"
                                    stroke-dasharray="31.416" stroke-dashoffset="31.416">
                                    <animate attributeName="stroke-dasharray" dur="2s"
                                        values="0 31.416;15.708 15.708;0 31.416" repeatCount="indefinite" />
                                    <animate attributeName="stroke-dashoffset" dur="2s" values="0;-15.708;-31.416"
                                        repeatCount="indefinite" />
                                </circle>
                            </svg>
                            上传中...
                        </span>
                    </button>
                </div>
            </form>

            <!-- 上传结果显示 -->
            <div v-if="uploadResult" class="upload-result" :class="uploadResult.type">
                <div class="result-icon">
                    <svg v-if="uploadResult.type === 'success'" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                    </svg>
                    <svg v-else fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12">
                        </path>
                    </svg>
                </div>
                <div class="result-content">
                    <h3>{{ uploadResult.title }}</h3>
                    <p>{{ uploadResult.message }}</p>
                    <button v-if="uploadResult.type === 'success'" @click="goToChat" class="goto-chat-btn">
                        去聊天
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const formData = ref({
    title: '',
    source: ''
})

const selectedFile = ref(null)
const isUploading = ref(false)
const isDragOver = ref(false)
const uploadResult = ref(null)

// API 基础 URL
const API_BASE_URL = 'http://localhost:5206/api'

// 文件选择处理
const handleFileSelect = (event) => {
    const file = event.target.files[0]
    if (file) {
        selectedFile.value = file
        if (!formData.value.title) {
            formData.value.title = file.name.replace(/\.[^/.]+$/, "")
        }
    }
}

// 拖拽处理
const handleDragOver = () => {
    isDragOver.value = true
}

const handleDragLeave = () => {
    isDragOver.value = false
}

const handleDrop = (event) => {
    isDragOver.value = false
    const files = event.dataTransfer.files
    if (files.length > 0) {
        selectedFile.value = files[0]
        if (!formData.value.title) {
            formData.value.title = files[0].name.replace(/\.[^/.]+$/, "")
        }
    }
}

// 清除文件
const clearFile = () => {
    selectedFile.value = null
    const fileInput = document.getElementById('file')
    if (fileInput) {
        fileInput.value = ''
    }
}

// 文件大小格式化
const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 上传文档
const uploadDocument = async () => {
    if (!selectedFile.value) {
        uploadResult.value = {
            type: 'error',
            title: '上传失败',
            message: '请选择要上传的文件'
        }
        return
    }

    if (!formData.value.title.trim()) {
        uploadResult.value = {
            type: 'error',
            title: '上传失败',
            message: '请填写文档标题'
        }
        return
    }

    isUploading.value = true
    uploadResult.value = null

    try {
        const formDataToSend = new FormData()
        formDataToSend.append('file', selectedFile.value)
        formDataToSend.append('title', formData.value.title.trim())
        formDataToSend.append('source', formData.value.source.trim() || '用户上传')

        const response = await fetch(`${API_BASE_URL}/document`, {
            method: 'POST',
            body: formDataToSend
        })

        if (response.ok) {
            const result = await response.json()
            uploadResult.value = {
                type: 'success',
                title: '上传成功',
                message: `文档 "${formData.value.title}" 已成功上传并处理完成`
            }

            // 重置表单
            formData.value = { title: '', source: '' }
            clearFile()
        } else {
            const errorText = await response.text()
            uploadResult.value = {
                type: 'error',
                title: '上传失败',
                message: errorText || '上传文档时发生错误'
            }
        }
    } catch (error) {
        console.error('Upload error:', error)
        uploadResult.value = {
            type: 'error',
            title: '上传失败',
            message: '网络错误，请检查服务器连接'
        }
    } finally {
        isUploading.value = false
    }
}

// 跳转到聊天页面
const goToChat = () => {
    router.push('/chat')
}
</script>

<style scoped>
.upload-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    max-width: 1400px;
    margin: 0 auto;
    padding: 2rem;
    width: 100%;
    min-height: calc(100vh - 70px);
}

.upload-header {
    text-align: center;
    margin-bottom: 2rem;
    padding: 2.5rem 2rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.upload-header h1 {
    margin-bottom: 1rem;
    font-size: 2.5rem;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.upload-header p {
    font-size: 1.2rem;
    opacity: 0.9;
    margin: 0;
    line-height: 1.6;
}

.upload-form {
    flex: 1;
    background: white;
    padding: 2.5rem;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    border: 1px solid rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
}

.form {
    display: grid;
    gap: 2.5rem;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.form-group label {
    font-weight: 600;
    color: #2c3e50;
    font-size: 1.1rem;
}

.form-input {
    padding: 1rem;
    border: 2px solid #e9ecef;
    border-radius: 10px;
    font-size: 1rem;
    transition: all 0.3s ease;
    background: #f8f9fa;
}

.form-input:focus {
    outline: none;
    border-color: #3498db;
    background: white;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.file-upload-area {
    border: 3px dashed #dee2e6;
    border-radius: 12px;
    padding: 3rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    background: #f8f9fa;
    min-height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.file-upload-area:hover,
.file-upload-area.dragover {
    border-color: #3498db;
    background: rgba(52, 152, 219, 0.05);
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(52, 152, 219, 0.15);
}

.file-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1.5rem;
}

.upload-icon {
    width: 5rem;
    height: 5rem;
    color: #3498db;
}

.upload-placeholder p {
    font-size: 1.2rem;
    color: #2c3e50;
    font-weight: 500;
    margin: 0;
}

.file-types {
    font-size: 1rem;
    color: #7f8c8d;
    margin: 0;
}

.file-selected {
    display: flex;
    align-items: center;
    gap: 1.5rem;
    text-align: left;
    background: white;
    padding: 1.5rem;
    border-radius: 10px;
    border: 2px solid #3498db;
    width: 100%;
    max-width: 500px;
    margin: 0 auto;
}

.file-icon {
    width: 3.5rem;
    height: 3.5rem;
    color: #3498db;
    flex-shrink: 0;
}

.file-info {
    flex: 1;
}

.file-name {
    font-weight: 600;
    color: #2c3e50;
    margin: 0 0 0.5rem 0;
    font-size: 1.1rem;
}

.file-size {
    color: #7f8c8d;
    font-size: 0.95rem;
    margin: 0;
}

.clear-file-btn {
    width: 2.5rem;
    height: 2.5rem;
    border: none;
    background: #e74c3c;
    color: white;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: all 0.3s ease;
}

.clear-file-btn:hover {
    background: #c0392b;
    transform: scale(1.1);
}

.clear-file-btn svg {
    width: 1.2rem;
    height: 1.2rem;
}

.form-actions {
    display: flex;
    justify-content: center;
    margin-top: 1rem;
}

.upload-btn {
    background: linear-gradient(135deg, #3498db, #2980b9);
    color: white;
    border: none;
    padding: 1rem 3rem;
    border-radius: 10px;
    font-size: 1.1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
    min-width: 180px;
    justify-content: center;
}

.upload-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}

.upload-btn:disabled {
    background: #bdc3c7;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

.uploading {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.spinner {
    width: 1.3rem;
    height: 1.3rem;
}

.upload-result {
    margin-top: 2rem;
    padding: 1.5rem;
    border-radius: 12px;
    display: flex;
    align-items: flex-start;
    gap: 1.5rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.upload-result.success {
    background: linear-gradient(135deg, #d4edda, #c3e6cb);
    border: 1px solid #28a745;
    color: #155724;
}

.upload-result.error {
    background: linear-gradient(135deg, #f8d7da, #f5c6cb);
    border: 1px solid #dc3545;
    color: #721c24;
}

.result-icon svg {
    width: 2rem;
    height: 2rem;
    flex-shrink: 0;
}

.result-content h3 {
    margin: 0 0 0.75rem 0;
    font-size: 1.2rem;
    font-weight: 600;
}

.result-content p {
    margin: 0 0 1rem 0;
    line-height: 1.6;
}

.goto-chat-btn {
    background: linear-gradient(135deg, #27ae60, #229954);
    color: white;
    border: none;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(39, 174, 96, 0.3);
}

.goto-chat-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(39, 174, 96, 0.4);
}

/* PC端响应式布局 */
@media (max-width: 1200px) {
    .upload-container {
        padding: 1.5rem;
    }

    .upload-header {
        padding: 2rem 1.5rem;
    }

    .upload-header h1 {
        font-size: 2.2rem;
    }

    .upload-form {
        padding: 2rem;
    }
}

@media (max-width: 992px) {
    .upload-container {
        padding: 1rem;
    }

    .upload-header {
        padding: 1.8rem 1rem;
        margin-bottom: 1.5rem;
    }

    .upload-header h1 {
        font-size: 2rem;
    }

    .upload-header p {
        font-size: 1.1rem;
    }

    .upload-form {
        padding: 1.8rem;
    }

    .file-upload-area {
        padding: 2rem;
        min-height: 150px;
    }
}

@media (max-width: 768px) {
    .upload-header h1 {
        font-size: 1.8rem;
    }

    .upload-form {
        padding: 1.5rem;
    }

    .form {
        gap: 2rem;
    }

    .file-upload-area {
        padding: 1.5rem;
        min-height: 120px;
    }

    .upload-icon {
        width: 4rem;
        height: 4rem;
    }

    .file-selected {
        flex-direction: column;
        text-align: center;
        gap: 1rem;
        max-width: 100%;
    }

    .upload-btn {
        padding: 0.875rem 2rem;
        width: 100%;
        max-width: 300px;
    }
}
</style>
